﻿using Microsoft.AspNetCore.Mvc.Filters;
using WomanMotion.WebApi.Infrastructure.XSS;
using System.Collections;
using Newtonsoft.Json.Linq;

namespace WomanMotion.WebApi.Api.Utility
{
    /// <summary>
    /// XSS 过滤器
    /// </summary>
    public class XSSFilterAttribute : ActionFilterAttribute
    {
        //在调用Action方法之前调用
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            //获取Action参数集合
            var ps = context.ActionDescriptor.Parameters;
            //遍历参数集合
            foreach (var p in ps)
            {
                if (context.ActionArguments[p.Name] != null)
                {
                    //当参数等于字符串
                    if (p.ParameterType.Equals(typeof(string)))
                    {
                        context.ActionArguments[p.Name] = XSSHelper.HtmlFilter(context.ActionArguments[p.Name].ToString());
                    }
                    else if (p.ParameterType.IsClass)//当参数等于类
                    {
                        ModelFieldFilter(context.ActionArguments[p.Name]);
                    }
                }

            }
        }

        private object ModelFieldFilter(object obj)
        {
            if (obj == null) return null;
            Type t = obj.GetType();

            if (obj is ICollection)
            {
                foreach (var item in obj as ICollection)
                {
                    ModelFieldFilter(item);
                }
            }
            else
            {
                
                //获取类的属性集合
                var pros = t.GetProperties();

                foreach (var pro in pros)
                {
                    var objtype = t.Name;
                    if (objtype == "String")
                    {
                        obj = XSSHelper.HtmlFilter(obj.ToString());
                        return obj;
                    }
                    if (pro.GetValue(obj) != null)
                    {
                        //当属性等于字符串
                        if (pro.PropertyType.Equals(typeof(string)))
                        {
                            string value = pro.GetValue(obj).ToString();
                            if (string.IsNullOrWhiteSpace(value))
                                continue;

                            pro.SetValue(obj, XSSHelper.HtmlFilter(value));
                        }
                        else if (pro.PropertyType.IsClass)//当属性等于类进行递归
                        {
                            pro.SetValue(obj, ModelFieldFilter(pro.GetValue(obj)));
                        }
                    }

                }
            }
            return obj;
        }
    }
}
